package ique.mantianx.controller;


import ique.mantianx.pojo.Books;
import ique.mantianx.service.BookService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

/**
 * @author starrysky
 * @title: BookController
 * @projectName book-system
 * @description: controller layer
 * @date 2021/2/521:27
 */
@Controller
@RequestMapping("/books")
public class BookController {

    @Autowired
    @Qualifier("BookServicelmpl")
    private BookService bookService;

    @GetMapping("/allBook")
    public String list(Model model) {
        List<Books> books = bookService.queryAllBooks();
        model.addAttribute("list_books", books);
        return "allBook";
    }

    @RequestMapping("/addOneBook")
    public String forwordAddPages() {
        return "addBook";
    }

    @PostMapping("/addBook")
    public String addBook(Books books) {
        bookService.inertBook(books);
        System.out.println("用户插入一本书" + "===>" + books);
        return "redirect:/books/allBook";
    }

    @GetMapping("/del/{bookId}")
    public String delOneBook(@PathVariable("bookId") Integer id) {
        int status = bookService.deleteBook(id);
        System.out.println("用户删除一本书状态：" + status);
        return "redirect:/books/allBook";
    }

    @GetMapping("/toUpdateBook")
    public String forwordUpdatePage(ModelMap modelMap, @Param("id") Integer id) {
        Books books = bookService.selectBook(id);
        modelMap.addAttribute("bok", books);
        System.out.println("用户正在修改" + "===>" + books);
        return "updateBook";
    }

    @PostMapping("/updateBook")
    public String updateOneBook(ModelMap modelMap, Books books) {
        int status = bookService.updateBook(books);
        Books books1 = bookService.selectBook(books.getBookId());
        System.out.println("用户修改书原信息状态：" + books);
        return "redirect:/books/allBook";
    }

    @PostMapping("/searchBook")
    public String searchBook( String queryBookName, ModelMap modelMap) {
        Books books = bookService.queryBookName(queryBookName);
        System.err.println(books);
        List<Books> bookList = new ArrayList<>();
        bookList.add(books);

        if (books==null){
            bookList = bookService.queryAllBooks();
            modelMap.addAttribute("error","没有找到你要的书!");
        }
        modelMap.addAttribute("list_books", bookList);
        return "allBook";
    }
}
